#!/bin/bash
set -e

### BEGIN INIT INFO
# Provides:           sslocal
# Required-Start:     $syslog $remote_fs
# Required-Stop:      $syslog $remote_fs
# Should-Start:
# Should-Stop:
# Default-Start:      2 3 4 5
# Default-Stop:       0 1 6
# Short-Description:  sslocal daemon for hyper.sh
# Description:
### END INIT INFO

export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

# BASE=$(basename $0)
BASE=sslocal

SSLOCAL=/usr/local/bin/$BASE
# This pid file is managed by start-stop-daemon
SSLOCAL_SSD_PIDFILE=/var/run/$BASE-ssd.pid
SSLOCAL_LOGFILE=/var/log/$BASE.log
SSLOCAL_DESC="sslocal"

# Get lsb functions
. /lib/lsb/init-functions

# Check sslocal is present
if [ ! -x $SSLOCAL ]; then
    log_failure_msg "$SSLOCAL not present or not executable"
    exit 1
fi

fail_unless_root() {
    if [ "$(id -u)" != '0' ]; then
        log_failure_msg "$SSLOCAL_DESC must be run as root"
        exit 1
    fi
}


case "$1" in
    start)
        fail_unless_root
        touch "$SSLOCAL_LOGFILE"

        log_begin_msg "Starting $SSLOCAL_DESC: $BASE"
        start-stop-daemon --start --background \
            --no-close \
            --exec "$SSLOCAL" \
            --pidfile "$SSLOCAL_SSD_PIDFILE" \
            --make-pidfile \
            -- "-c/etc/shadowsocks.json" \
                    >> "$SSLOCAL_LOGFILE" 2>&1
        log_end_msg $?
        ;;

    stop)
        fail_unless_root
        log_begin_msg "Stopping $SSLOCAL_DESC: $BASE"
        start-stop-daemon --stop --pidfile "$SSLOCAL_SSD_PIDFILE"
        log_end_msg $?
        ;;

    restart)
        fail_unless_root
        SSLOCAL_PID=`cat "$SSLOCAL_SSD_PIDFILE" 2>/dev/null`
        [ -n "${SSLOCAL_PID}" ] \
            && ps -p ${SSLOCAL_PID} > /dev/null 2>&1 \
            && $0 stop
        $0 start
        ;;

    force-reload)
        fail_unless_root
        $0 restart
        ;;

    status)
        status_of_proc -p "$SSLOCAL_SSD_PIDFILE" "$SSLOCAL" "$SSLOCAL_DESC"
        ;;

    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac
